package com.lw.leetcode.greedy.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * greedy
 * 1686. 石子游戏 VI
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/25 15:25
 */
public class StoneGameVI {


    public static void main(String[] args) {
        StoneGameVI test = new StoneGameVI();

        // 1
        int[] aliceValues = {1, 3};
        int[] bobValues = {2, 1};

        // 0
//        int[] aliceValues = {1, 2};
//        int[] bobValues = {3, 1};

        // -1
//        int[] aliceValues = {2, 4, 3};
//        int[] bobValues = {1, 6, 7};

        // -1
//        int[] aliceValues = {2, 9, 1, 1, 1, 3, 5, 8, 8, 6, 8, 6, 2, 4};
//        int[] bobValues = {1, 9, 7, 8, 3, 4, 2, 7, 8, 10, 1, 7, 10, 4};

        int i = test.stoneGameVI(aliceValues, bobValues);
        System.out.println(i);
    }


    public int stoneGameVI(int[] aliceValues, int[] bobValues) {
        int m = aliceValues.length;
        if (m == 1) {
            return 1;
        }
        for (int i = 0; i < m; i++) {
            aliceValues[i] = ((bobValues[i] + aliceValues[i]) << 8) + aliceValues[i];
        }
        Arrays.sort(aliceValues);
        int a = 0;
        int b = 0;
        if ((m & 1) == 1) {
            a += (aliceValues[m - 1] & 0XFF);
            for (int i = m - 2; i > 0; i -= 2) {
                b += (aliceValues[i] >> 8) - (aliceValues[i] & 0XFF);
                a += aliceValues[i - 1] & 0XFF;
            }
        } else {
            for (int i = m - 1; i > 0; i -= 2) {
                a += aliceValues[i] & 0XFF;
                b += (aliceValues[i - 1] >> 8) - (aliceValues[i - 1] & 0XFF);
            }
        }
        if (a == b) {
            return 0;
        } else if (a > b) {
            return 1;
        }
        return -1;
    }


    private int[] getArr(int length) {
        int[] arr = new int[length];

        for (int i = 0; i < length; i++) {
            arr[i] = (int) (Math.random() * 100);
        }
        return arr;
    }


    public int stoneGameVI2(int[] aliceValues, int[] bobValues) {
        int m = aliceValues.length;
        if (m == 1) {
            return 1;
        }
        int n = (m + 1) >> 1;
        int[][] arr = new int[m + 1][n + 1];

//        arr[1][1] = aliceValues[0];
//        int sum = 0;
        for (int i = 1; i <= m; i++) {
            int l = Math.min(i, n);
            arr[i][0] = arr[i - 1][0] - bobValues[i - 1];
            for (int j = 1; j <= l; j++) {
                arr[i][j] = Math.max(arr[i - 1][j - 1] + aliceValues[i - 1], arr[i - 1][j] - bobValues[i - 1]);
            }
        }
        for (int[] ints : arr) {
            System.out.println(Arrays.toString(ints));
        }
        int i = arr[m][n];
        if (i > 0) {
            return 1;
        } else if (i < 0) {
            return -1;
        }
        return 0;
    }

}
